using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Diagnostics;


namespace RssReader.Common
{
    public class RssReader
    {

        XNamespace slashNamespace = "http://purl.org/rss/1.0/modules/slash/";

        public IEnumerable<RssEntry> Posts { get; private set; }
        

        public void GetFeed(string url, Action<IEnumerable<RssEntry>> completed)
        {

            WebClient client = new WebClient();
            client.DownloadStringCompleted += (s, e) =>
                {
                    try
                    {
                        XDocument rssFeed = XDocument.Parse(e.Result);
                        var posts = from item in rssFeed.Descendants("item")
                                    select new RssEntry
                                    {
                                        Header = item.Element("title").Value,
                                        Published = DateTime.Parse(item.Element("pubDate").Value),
                                        Url = item.Element("link").Value,
                                        Description = item.Element("description").Value,
                                        Tags = (from category in item.Elements("category")
                                                orderby category.Value
                                                select category.Value).ToList()
                                    };

                        completed (posts);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                
                };

            client.DownloadStringAsync(new Uri(url));

            //Let us wait, because this is already in a background thread.
            
        }
    }

}
